package com.zys.background.common.config;

import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.BlockAttackInnerInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.OptimisticLockerInnerInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.reflection.MetaObject;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import java.util.Date;

/**
 * @author zys
 * @since 2022-11-14
 */
@Configuration
@EnableAutoConfiguration
@EnableTransactionManagement
@MapperScan("com.zys.background.**.mapper")
public class MybatisPlusConfiguration {
  /**
   * mybatis-plus 拦截器链
   *
   * @return MybatisPlusInterceptor
   */
  @Bean
  public Interceptor mybatisPlusInterceptor() {
    MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
    // 分页插件
    interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
    // 乐观锁
    interceptor.addInnerInterceptor(new OptimisticLockerInnerInterceptor());
    // sql 性能规范, 即必须走索引
    // interceptor.addInnerInterceptor(new IllegalSQLInnerInterceptor());
    // 防止全表更新与删除
    interceptor.addInnerInterceptor(new BlockAttackInnerInterceptor());

    return interceptor;
  }

  /**
   * 需要自动填充的列, 如创建时间、修改时间
   *
   * @return MetaObjectHandler
   */
  @Bean
  public MetaObjectHandler metaObjectHandler() {
    return new MetaObjectHandler() {
      @Override
      public void insertFill(MetaObject metaObject) {
        this.strictInsertFill(metaObject, "create_time", Date.class, new Date()); // 创建时间
        this.strictInsertFill(metaObject, "modify_time", Date.class, new Date()); // 修改时间
        // 添加人
        // 修改人
      }

      @Override
      public void updateFill(MetaObject metaObject) {
        this.strictInsertFill(metaObject, "modify_time", Date.class, new Date()); // 修改时间
        // 修改人
      }
    };
  }
}
